package com.pdstudio.weather;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.Set;

import android.app.TabActivity;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

import com.pdstudio.app.Application;
import com.pdstudio.bean.SimpleCity;
import com.pdstudio.bean.WeatherProfile;
import com.pdstudio.charts.StationCurrentStateActivity;
import com.pdstudio.http.WeatherHttpMethod;
import com.pdstudio.util.SharePreferenceUtil;

public class MainActivity extends TabActivity implements
		Application.EventHandler {

	TabHost tabHost;// 底部tab控件

	private ImageView tShareBtn;

	private RadioButton navHomeBtn, navStationBtn, navRadarBtn, navWaterBtn,
			navCloudBtn;// 底部导航按钮

	private View customTitleView;
	private ImageView imgHome;// 首页图标
	private ImageView imgProducts;// 所有产品
	// private ImageButton imgProducts;
	private ImageView imgSettings;// 系统设置
	private TextView txtTitle;

	private long mExitTime;
	private Integer mBgResId;

	private SharePreferenceUtil mSpUtil;
	private Application mApplication;

	private Handler handler = null;
	private WeatherProfile mWeatherProfile;
	private final String JPUSHTESTALIAS = "version1215";

	// 获取天气实况
	private final int MESSAGE_GETWEATHERPROFILE = 1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		// handler与线程之间的通信及数据处理
		handler = new Handler() {
			public void handleMessage(Message msg) {
				if (msg.what == MESSAGE_GETWEATHERPROFILE) {
					try {
						Toast.makeText(getApplicationContext(), "加载天气数据中",
								Toast.LENGTH_SHORT).show();
						// msg.obj是获取handler发送信息传来的数据

						if (msg != null && msg.obj != null) {
							mWeatherProfile = (WeatherProfile) msg.obj;
						}
						setForecast(mWeatherProfile);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}

		};

		Application.mListeners.add(this);
		mApplication = Application.getInstance();
		mSpUtil = mApplication.getSharePreferenceUtil();

		// 获取用户授权preference对象

		if (mSpUtil.getAuthCode().equals("")) {
			Intent intent = new Intent(this, UserAuthActivity.class);
			startActivity(intent);
		}

		// initTab();
		// initView();
		// initBackground();

		customTitleView = findViewById(R.id.title);
		txtTitle = (TextView) customTitleView.findViewById(R.id.title_text_nav);
		txtTitle.setText(mApplication.getCurSimpleCity().cityName);

		// 设置顶部导航条的按钮
		setImageViewHome();
		setImageProducts();
		setImageSettings();
		getVersion();
		
		// 设置极光push的别名，测试用，发布新包时请注意修改
		setPushAlias();

	}

	private static final int MSG_SET_ALIAS = 1001;
	private final Handler mHandler = new Handler() {
		@Override
		public void handleMessage(android.os.Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case MSG_SET_ALIAS:
				// Log.d(TAG, "Set alias in handler.");
				// 调用 JPush 接口来设置别名。
				JPushInterface.setAliasAndTags(getApplicationContext(),
						(String) msg.obj, null, mAliasCallback);
				break;
			default:
				// Log.i(TAG, "Unhandled msg - " + msg.what);
			}
		}
	};

	private final TagAliasCallback mAliasCallback = new TagAliasCallback() {
		@Override
		public void gotResult(int code, String alias, Set<String> tags) {
			String logs;
			switch (code) {
			case 0:
				logs = "Set tag and alias success";
				// Log.i(TAG, logs);
				// 建议这里往 SharePreference 里写一个成功设置的状态。成功设置一次后，以后不必再次设置了。
				break;
			case 6002:
				logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
				// Log.i(TAG, logs);
				// 延迟 60 秒来调用 Handler 设置别名
				mHandler.sendMessageDelayed(
						mHandler.obtainMessage(MSG_SET_ALIAS, alias), 1000 * 60);
				break;
			default:
				logs = "Failed with errorCode = " + code;
				// Log.e(TAG, logs);
			}
			// ExampleUtil.showToast(logs, getApplicationContext());
		}
	};

	private void setPushAlias() {
		// 调用 Handler 来异步设置别名
		mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS,
				JPUSHTESTALIAS));

	}

	@Override
	protected void onResume() {
		super.onResume();
		// setContentView(R.layout.activity_main);
		// 获取用户授权preference对象
		// mApplication = Application.getInstance();
		// mSpUtil = mApplication.getSharePreferenceUtil();

		if (mSpUtil.getAuthCode().equals("")) {
			Intent intent = new Intent(this, UserAuthActivity.class);
			startActivity(intent);
		}

		initTab();
		initView();
		initBackground();

		customTitleView = findViewById(R.id.title);
		txtTitle = (TextView) customTitleView.findViewById(R.id.title_text_nav);
		txtTitle.setText(mApplication.getCurSimpleCity().cityName);

		// 设置顶部导航条的按钮
		setImageViewHome();
		setImageProducts();
		setImageSettings();
		// getVersion();

	}

	/**
	 * 获取版本号
	 * 
	 * @return 当前应用的版本号
	 */
	public String getVersion() {
		try {
			PackageManager manager = this.getPackageManager();
			PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0);
			String version = info.versionName;
			return this.getString(R.string.version_name) + version;
		} catch (Exception e) {
			e.printStackTrace();
			return this.getString(R.string.can_not_find_version_name);
		}
	}

	private void setImageSettings() {
		imgSettings = (ImageView) customTitleView
				.findViewById(R.id.title_img_right_two);
		// imgSettings.setImageDrawable(getResources().getDrawable(
		// R.drawable.top_setting));
		imgSettings.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(MainActivity.this,
						SettingsActivity.class);
				startActivity(intent);
			}

		});
	}

	private void setImageProducts() {
		imgProducts = (ImageView) customTitleView
				.findViewById(R.id.title_img_right_one);
		// imgProducts.setImageDrawable(getResources().getDrawable(
		// R.drawable.top_products_background));
		imgProducts.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				UnEnableButton();
				tabHost.setCurrentTabByTag("tabProducts");
				// Intent intent = new
				// Intent(MainActivity.this,ProductsActivity.class);
				// startActivity(intent);
			}
		});
	}

	private void setImageViewHome() {
		imgHome = (ImageView) customTitleView.findViewById(R.id.title_img_main);
		// TODO:这里要根据当前运行的activity来设置不同的图标和OnClickListener()
		// imgHome.setImageDrawable(getResources().getDrawable(
		// R.drawable.title_city_list));
		imgHome.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MainActivity.this,
						AddCitysActivity1.class);
				startActivity(intent);
			}

		});
	}

	private void initBackground() {

		// 开一条子线程加载网络数据
		Runnable runnable = new Runnable() {
			@Override
			public void run() {
				try {
					Thread.sleep(0);
					WeatherHttpMethod whm = new WeatherHttpMethod(
							getApplicationContext());
					WeatherProfile actual = whm.Getweatherforecasts(
							mSpUtil.getAuthCode(),
							mApplication.getCurSimpleCity().cityCode);
					Message m = handler.obtainMessage(
							MESSAGE_GETWEATHERPROFILE, actual);
					handler.sendMessage(m);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		};

		try {
			// 开启线程
			new Thread(runnable).start();
		} catch (Exception e) {
			e.printStackTrace();
		}

		LinearLayout layout = (LinearLayout) findViewById(R.id.main);
		int resId = mApplication.getApplicationBackground(mSpUtil
				.getWeatherStatus());
		layout.setBackground(getResources().getDrawable(resId));

	}

	private void setForecast(WeatherProfile weatherProfile) {
		mSpUtil.setWeatherStatus(weatherProfile.weatherStatus);
	}

	private void initView() {

		navHomeBtn = (RadioButton) findViewById(R.id.nav_home_city);
		navStationBtn = (RadioButton) findViewById(R.id.nav_weather_station);
		navWaterBtn = (RadioButton) findViewById(R.id.nav_weather_water);
		navRadarBtn = (RadioButton) findViewById(R.id.nav_weather_radar);
		navCloudBtn = (RadioButton) findViewById(R.id.nav_weather_cloud);

		navHomeBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				UnEnableButton();
				navHomeBtn.setChecked(true);
				tabHost.setCurrentTabByTag("tab1");

			}
		});

		navStationBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				UnEnableButton();
				navStationBtn.setChecked(true);
				tabHost.setCurrentTabByTag("tab2");

			}
		});

		navRadarBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				UnEnableButton();
				navRadarBtn.setChecked(true);
				tabHost.setCurrentTabByTag("tab3");

			}
		});

		navWaterBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				UnEnableButton();
				navWaterBtn.setChecked(true);
				tabHost.setCurrentTabByTag("tabWater");

			}
		});

		navCloudBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				UnEnableButton();
				navCloudBtn.setChecked(true);
				tabHost.setCurrentTabByTag("tab5");

			}
		});

	}

	@Override
	public void onCityComplite() {
		// do nothing
	}

	@Override
	public void onNetChange() {

	}

	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		if (event.getKeyCode() == KeyEvent.KEYCODE_BACK
				&& event.getAction() == KeyEvent.ACTION_DOWN) {
			if ((System.currentTimeMillis() - mExitTime) > 2000) {
				Object mHelperUtils;
				Toast.makeText(this, "再按一次退出！", Toast.LENGTH_SHORT).show();
				mExitTime = System.currentTimeMillis();

			} else {
				finish();
			}
			return true;
		}
		return super.dispatchKeyEvent(event);
	}

	private void initTab() {
		// Intent tabIntent = new Intent(this, ForecastActivity.class);
		Bundle bundle = new Bundle();
		SimpleCity sc = mApplication.getCurSimpleCity();
		if (sc != null) {
			bundle.putString("address", sc.cityCode);
		} else {
			bundle.putString("address", "岳阳");
		}
		// tabIntent.putExtras(bundle);

		tabHost = getTabHost();
		// tabHost.addTab(tabHost.newTabSpec("tab1").setIndicator("tab1")
		// .setContent(tabIntent));
		tabHost.addTab(tabHost
				.newTabSpec("tab1")
				.setIndicator("tab1")
				.setContent(
						new Intent(this, ForecastActivity.class).putExtra(
								"address", sc.cityCode)));
		tabHost.addTab(tabHost
				.newTabSpec("tab2")
				.setIndicator("tab2")
				.setContent(new Intent(this, StationCurrentStateActivity.class)));
		tabHost.addTab(tabHost.newTabSpec("tab3").setIndicator("tab3")
				.setContent(new Intent(this, RedaImageActivity.class)));
		tabHost.addTab(tabHost.newTabSpec("tabWater").setIndicator("tabWater")
				.setContent(new Intent(this, WaterActivity.class)));
		tabHost.addTab(tabHost.newTabSpec("tab5").setIndicator("tab5")
				.setContent(new Intent(this, CloudImageActivity.class)));
		tabHost.addTab(tabHost.newTabSpec("tabProducts")
				.setIndicator("tabProducts")
				.setContent(new Intent(this, ProductsActivity.class)));

	}

	/*
	 * 去掉所有按钮的背景
	 */
	private void UnEnableButton() {
		navHomeBtn.setChecked(false);
		navStationBtn.setChecked(false);
		navRadarBtn.setChecked(false);
		navWaterBtn.setChecked(false);
		navCloudBtn.setChecked(false);
	}

}
